package com.shawn.datastructure.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {

	public List<List<Integer>> threeSum(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
		if (nums == null || nums.length < 3) {
			return result;
		}
		int n = nums.length;
		Arrays.sort(nums);

		for (int i = 0; i < n; i++) {
			// 找到负数
			if (nums[i] > 0) {
				break;
			}

			// 过滤重复
			if (i > 0 && nums[i] == nums[i - 1]) {
				continue;
			}

			int head = i + 1;
			int tail = n - 1;
			int val = 0 - nums[i];

			while (head < tail) {
				int data = nums[head] + nums[tail];
				if (data == val) {
					result.add(Arrays.asList(nums[i], nums[head], nums[tail]));
					while (head < tail && nums[tail] == nums[tail - 1]) {
						tail--;
					}
					while (head < tail && nums[head] == nums[head + 1]) {
						head++;
					}
					head++;
					tail--;
				} else if (data < val) {
					head++;
				} else {
					tail--;
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		ThreeSum sum = new ThreeSum();
		int[] nums = {-1, 0, 1, 2, -1, -4};
		sum.threeSum(nums);
	}

}
